#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "log.h"



#ifdef LOGGING

FILE* logFile=NULL;


int log_init() {
	long fnamelen=0;
	_TCHAR * fname=NULL;
	
	//get current directory
	fnamelen=GetCurrentDirectory(fnamelen,fname)+15;//+space for filename
	fname=new _TCHAR[fnamelen];
	GetCurrentDirectory(fnamelen,fname);
	//append filename
	_tcscat(fname,_T("\\tracelog.log"));
	//open file
	logFile = _tfopen(fname, _T("wt"));
	if ( logFile == NULL ) {
		logFile = stderr;
		return 0;
	}
	return 1;
}

void log(const _TCHAR* szFmt,...) {
	va_list args;
	va_start(args, szFmt);
	_vftprintf(logFile, szFmt, args);
	fflush(logFile);
	va_end(args);
}

void log_finit() {
	fclose(logFile);
}

//logs information about last system error
//if error was not specified it will be obtained by GetLastError() function
BOOL log_error(_TCHAR * funcname,int err) {
	LPVOID	lpMsgBuf=NULL;
	if(!err)err=GetLastError();
	if(err){
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			NULL,err,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			(LPTSTR) &lpMsgBuf,0,NULL);
		log(_T("ERR: %s:%s\n"),funcname,lpMsgBuf);
	}else{
		log(_T("ERR: %s:No error?\n"),funcname);
	}
	return 0;
}
#endif
